$.datepicker.setDefaults({ showAnim: 'fadeIn' });
$(document).ready(function() {	
	$("#main_menu").width($(window).width() - 30);
	$(".calendar").datepicker({
		showAnim: 'fadeIn'
	});
	
	$("#generic_place_lnk").click(function(){			
		if($("#event_place_attributes_is_generic").is(":checked")){				
			$("#event_place_search_field").show();
			$("#event_location_search_field").hide();				
			$("#event_place_attributes_is_generic").removeAttr('checked');
			$("#generic_place_lnk").attr("class", "mini_button_form");
			$("#event_place_location_autocomplete_tip").hide();
			$("#event_place_autocomplete_tip").show();			
		}else{
			$("#event_place_search_field").hide();
			$("#event_location_search_field").show();	
			$("#event_place_autocomplete_tip").hide();
			$("#event_place_location_autocomplete_tip").show();
			$("#event_place_attributes_is_generic").attr('checked','checked');
			$("#generic_place_lnk").attr("class", "mini_button_form mini_button_form_clicked");			
		}
		return false;
	});
	
	
	$("#event_name").blur(function(){
		$.get("/events/auto_complete_for_name?q=" + $("#event_name").val() + "&date=" + $("#event_date").val(), function(data) {	    	
				events = eval(" (" + data + ") ");
				$('#existing_events_list_div').html("");					
				if (events.length > 0) {						
			  	$("#existing_events_div").show();				  	
			  	for (i = 0; i < events.length; i++) {
						element = "<a href='/events/view/" + events[i].id + "'><div style='display:none'class='existing_event title_sub' id='existing_event_" + events[i].id + "'>\
													" + events[i].name + "<br /> <span style='color:#555;'>"+
													events[i].place + "</span> <span style='color:#aaa;font-size:12px;'>" + events[i].location + "</span></div></a>"; 
			  		$('#existing_events_list_div').append(element);
						$("#existing_event_" + events[i].id).show("normal");				  		
			  	}
			  }
					    
	  });
	});
	
	$("input#user_location_attributes_full_address").autocomplete("/users/auto_complete_for_location",
			 { 
			 	 formatItem: function(item) {			 		
			 			return item[0]; 
					},
					onItemSelect: blockInputLocation,
					matchSubset: false
					
			 }		 
		 ).result(function(event, item){blockInputLocation('user_location_attributes_full_address')});
	  
	 $("input#location_menu").autocomplete("/users/auto_complete_for_location_full_address")
	 $("a#login_lnk").click(function () {
	 		$("a#login_lnk").addClass("login_lnk_onclick");
			$("div#location_div_main_menu").hide();
	 		$("div#login_div_main_menu").animate({ height: 250 }, 500);	 		
	 });
	 $("div#location_main_menu").click(function () {
				$("div#main_menu").animate({ height: 25 }, 150, "linear", function () {
				$("div#login_div_main_menu").animate({ height: 0 }, 50);
				$("a#login_lnk").removeClass("login_lnk_onclick");
				$("div#location_div_main_menu").show();	 		
				$("div#main_menu").animate({ height: 50 }, 150, "linear");
			});
	 });
	 
	 place_form_submited = false;
	 $("form#place_new_form").submit(function(){
	 		if(!place_form_submited)
			{
		  	place_form_submited = true;
				$.ajax({
		  		url: '/places/exist',
		  		data: {
		  			'name': $("input#place_name").val()
		  		},
		  		success: function(data){						
						if($.trim(data) != ""){
							$('div#existing_places').html(data);
							$('html, body').animate({
								scrollTop: $("#top_place_form").offset().top
							}, 400);
						}
						else {
							$("form#place_new_form").submit();
						}
		  		},
		  	});
		  } else return true;
			return false;			
	 	}
		
		
	 );
	

	 human_form_submited = false;
	 $("form#human_new_form").submit(function(){
	 		if(!human_form_submited)
			{
		  	human_form_submited = true;
				$.ajax({
		  		url: '/humans/exist',
		  		data: {
		  			'name': $("input#human_name").val()
		  		},
		  		success: function(data){
						if ($.trim(data) != "") {
							$('div#existing_humans').html(data);
							$('html, body').animate({
								scrollTop: $("#top_human_form").offset().top
							}, 400);
						}
						else{
							$("form#human_new_form").submit();
						}
		  		},
		  	});
		  } else return true;
			return false;			
	 	}
	 );


	$('a.more_site_lnk').click(function(){
		$("<p style='margin-top:5px;'><input type='text' size='30' name='" + $(this).attr('rel') + "[site][]' /></p>").hide()
		.appendTo($(this).parent()).fadeIn();		
		//$('a.more_site_lnk').parent().append("<p style='margin-top:5px;'><input size='30' type='text' name='" + $(this).attr('rel') + "[site][]' /></p>");
		return false;
	});
	
	$("div.super_kind").click(function(){		
		$("div.super_kind_clicked").attr("class","label_style super_kind");
		$(this).attr("class","label_style super_kind super_kind_clicked");
		rif= "#" + $(this).attr("rif");		
		$("div.kind_super_div_showed").fadeOut(200,function(){
			$(this).attr("class","kind_super_div");	
			$(rif).fadeIn("fast");	
			$(rif).attr("class","kind_super_div_showed");			
		});
		
	});


	$('div.kind_div').click(function(){		
		div_to_move = $(this);
		add_remove = $(".kind_add_remove", div_to_move);		
		td = add_remove.parents("td.kinds_cell_form");						
		if (add_remove.html() == "-" || 
			(add_remove.html() == "+" && $("div.kind_to div.kind_div", td).size() < 3)) {
			div_to_move.slideToggle(200, function(){
				if (add_remove.html() == "+") {
					add_remove.html("-");					
					$("div.kind_to", td).append(div_to_move);					
				}
				else {
					add_remove.html("+");										
					$("#" + div_to_move.attr("rif")).append(div_to_move);
				}
				
				txt_kinds = $("input.core_kinds_txt", $(td).parents("form.core_form"));
				txt_kinds.val("");
				$("div.kind_to div.kind_div",td).each(function(){
					txt_kinds.val(txt_kinds.val() + $(this).attr("kind") + ",") 
				});
				div_to_move.fadeIn();				
			});
		}
	});		

	if ($("textarea.tinymce").length > 0) {
		initTyniMce();
	}	
	
	$('.core_photo_slide').innerfade({ speed: 'slow', timeout: 8000, type: 'sequence' }); 

	$(".link_gray_ani").hover(function() {
		$(this).animate({ backgroundColor: "#ccc" }, 600);
	},function() {
		$(this).animate({ backgroundColor: "#eee" }, 400);
	});
 });

function blockInputLocation(id)
{		
	$("#location_name_readable").text($('#' + id).val());
	$('#location_name_readable').show();
	$('#edit_location_lnk').show();
	$("#" + id).hide();
}

function blockInputPlace(id, val, name)
{	
	if (val == 0) {  	
		$("#place_name").val(name);
		$("#modal_place_div").dialog("open"); 
		$("#place_location_attributes_full_address").focus();
		$("#event_place_attributes_name").val(name);
  }
  else {
  	$("#place_name_readable").text($('#' + id).val());
		$("#event_place_attributes_id").val(val);
  	$('#place_name_readable').show();
  	$('#generic_place_lnk').hide();
		$('#edit_place_lnk').show();
  	$("#event_place_search_field").hide();
  }
}

function blockInputEventLocation(id)
{		
	$("#place_name_readable").text($('#' + id).val());
	$('#place_name_readable').show();
	$('#generic_place_lnk').hide();
	$('#edit_place_lnk').show();
	$("#event_location_search_field").hide();	
}
function changeInputLocation(id)
{
	$('#location_name_readable').hide();
	$('#edit_location_lnk').hide();
	$("#" + id).val("");
	$("#" + id).show();
	return false;
}

function changeInputPlace(id)
{
	$('#place_name_readable').hide();	
	$('#generic_place_lnk').show();
	$('#edit_place_lnk').hide();
	$("#event_place_location_full_address").val("");	
	$("#" + id).val("");
	$("#event_place_attributes_id").val("");
	if ($("#event_place_attributes_is_generic").is(":checked")) 
  		$("#event_location_search_field").show();
  	else $('#event_place_search_field').show();
	return false;
}

function blockInputHuman(id, val, name)
{	
	if (val == 0) {		
		$("#human_name").val(name);
		$('#modal_human_div').dialog("open")		
		$("#event_human_names").val(name);		
  }else
	{
		$("#human_names").html($("#human_names").html() + "<span humanid='" + val +"' class='human_selected'>" + name + "<span class='close_human_selected'>X</span></span>");
		
		$("#event_human_ids").val($("#event_human_ids").val() + 
				($("#event_human_ids").val() != "" ? "," : "") + val);		
		$("#event_human_names").val("");
		$(".close_human_selected").click(function(){			
			$("#event_human_ids").val(("," + $("#event_human_ids").val() + ",").replace("," + 
				$(this).parent().attr("humanid") + ",", ","));
			ids = $("#event_human_ids").val();
			$("#event_human_ids").val(ids != "," ? ids.substring(1,ids.length - 1) : "");							
			$(this).parent().remove();
		});		
	}
}

function connectHumanFields()
{	
	initTyniMce("human_description")
	//$("#artist_tag_list").autocomplete(artist_tags, { multiple: true,	autoFill: true });
	
}


function connectPlaceFields()
{
	initTyniMce("place_description");
	$("input#place_location_attributes_full_address").autocomplete("/places/auto_complete_for_location",
			 { 
			 	 formatItem: function(item) {			 		
			 			return item[0]; 
					},
					onItemSelect: blockInputLocation,
					matchSubset: false
					
			 }		 
		 ).result(function(event, item){blockInputLocation('place_location_attributes_full_address')});
	//$("#place_tag_list").autocomplete(place_tags, { multiple: true, autoFill: true });	
	
}

function connectEventFields()
{
	initTyniMce("event_description");
	$("input#event_place_location_full_address").autocomplete("/places/auto_complete_for_location",
				 { 
				 	 formatItem: function(item) {			 		
				 			return item[0]; 
						},
						onItemSelect: blockInputEventLocation,
						matchSubset: false
						
				 }		 
			 ).result(function(event, item){blockInputEventLocation('event_place_location_full_address')});
			 
	$("input#event_human_names").autocomplete("/humans/auto_complete_for_name",
			 { 
			 	 formatItem: function(item) {			 		
			 			return item[0]; 
					},
				 onItemSelect: blockInputHuman,
				 matchSubset: false,
				 extraParams: {human_ids: function() { return $("#event_human_ids").val(); } },					
			 }
		 ).result(function(event, item){blockInputHuman('event_human_names',item[1], item[2])});
		 
	$("input#event_place_attributes_name").autocomplete("/places/auto_complete_for_name",
		 { 
		 	 formatItem: function(item) {			 		
		 			return item[0] + "<br /><h5>"+ item[1] + "</h5>";
				},
				onItemSelect: blockInputPlace,
				matchSubset: false
		 }		 
	 ).result(function(event, item){blockInputPlace('event_place_attributes_name',item[2], item[3])});

	
	$("#modal_place_div").dialog({
		bgiframe: true,
		autoOpen: false,
		open: function(event, ui) { initTyniMce("place_description") },
		beforeclose: function(event, ui) { 
			a = tinyMCE.get("place_description").remove(); 
		},
		width: 760,		
		position: ['center', 50],	
		modal: true});
		
	$("#modal_human_div").dialog({
		bgiframe: true,
		autoOpen: false,
		open: function(event, ui) { initTyniMce("human_description") },
		beforeclose: function(event, ui) { 
			a = tinyMCE.get("human_description").remove(); 
		},
		width: 760,		
		position: ['center', 50],	
		modal: true});		
}

function switchDiv(to_show,to_hide)
{
	$("#" + to_show).show();	
	$("#" + to_hide).hide();
}



function clickDayOfWeek(day){
	value = $("#event_days_of_week").val()
	if (value.indexOf(day + ",") == -1) {
		$("#event_days_of_week").val(value + day + ",");	
		$("#day_of_week_" + day).attr("class", "mini_button_form mini_button_form_clicked");
		$("#day_of_week_8").attr("class", "mini_button_form");			
	}
	else {	
		$("#event_days_of_week").val(value.replace(day + ",", ""));
		$("#day_of_week_" + day).attr("class", "mini_button_form");		
		if($("#event_days_of_week").val() == "")
			$("#day_of_week_8").attr("class", "mini_button_form mini_button_form_clicked");
	}
}

function partOfDayClicked(button,ele){
	button = $(button);
	field = $("#event_part_of_day");
	str = field.val();
	
	if(ele == 5){
		$("#part_of_day_field_div a").attr("class","mini_button_form");
		button.attr("class", "mini_button_form mini_button_form_clicked");
		field.val("1111");		
	}else if(str.charAt(ele - 1) == '0' || str == '1111')
	{			
		if (str == '1111') 
			str = '0000';
		$("#event_all_day_lnk").attr("class", "mini_button_form");
		str = replaceOneChar(str,'1',ele);				
		field.val(str);
		if(str == '1111')
		{
			$("#part_of_day_field_div a").attr("class", "mini_button_form");
			$("#event_all_day_lnk").attr("class","mini_button_form mini_button_form_clicked");
		}
		else
			button.attr("class", "mini_button_form mini_button_form_clicked");
	}else{		
		str = replaceOneChar(str,'0',ele);		
		field.val(str);
		button.attr("class", "mini_button_form");
		if (field.val() == '0000') {
			$("#event_all_day_lnk").attr("class", "mini_button_form mini_button_form_clicked");
			field.val('1111');
		}
	}
	return false;
}

function chkClicked(button, chkId)
{
	button = $(button);
	chk = $("#" + chkId);	
	if (chk.attr("checked")) {
		chk.removeAttr("checked");
		button.attr("class", "mini_button_form");
	}
	else {
		chk.attr("checked", "checked");
		button.attr("class", "mini_button_form mini_button_form_clicked");
	}
	
	return false;
		
}

function more_days_click()
{	
	if($("#more_days").attr("class") == "mini_button_form")
	{
		$("#more_days").attr("class", "mini_button_form mini_button_form_clicked");
		$('#event_date_end').val($("#event_date").val());
		$('#event_date').fadeOut(100, function(){
			$('#event_date').attr("style", "width:126px");
			$('#more_days_div').fadeIn(100);
			$('#label_from_date').fadeIn(100);
			$('#date_end_field_div').fadeIn(100);
		});		
		$('#more_days_container').attr("style", "margin-top:18px;");
	}else{
		$("#more_days").attr("class", "mini_button_form");
		$('#event_date').fadeOut(100);
		$('#more_days_div').fadeOut(100);
		$('#label_from_date').fadeOut(100);		
		$('#date_end_field_div').fadeOut(100,function(){
			$('#event_date_end').val($("#event_date").val());			
			$('#event_date').removeAttr("style");
			$('#more_days_container').removeAttr("style");
			$('#event_date').fadeIn(100);	
			clickAllDays();
		});
	}
}

function clickAllDays(){
	if($("#event_days_of_week").val() != ""){
		$("#event_days_of_week").val("");
		for (i = 0; i < 7; i++)
			$("#day_of_week_" + i).attr("class", "mini_button_form");
		$("#day_of_week_8").attr("class", "mini_button_form mini_button_form_clicked");
	}
}


$.fn.clearForm = function() {
  return this.each(function() {
 var type = this.type, tag = this.tagName.toLowerCase();
 if (tag == 'form')
   return $(':input',this).clearForm();
 if (type == 'text' || type == 'password' || tag == 'textarea')
   this.value = '';
 else if (type == 'checkbox' || type == 'radio')
   this.checked = false;
 else if (tag == 'select')
   this.selectedIndex = -1;
  });
};


function replaceOneChar(s,c,n){
	var re = new RegExp('^(.{'+ --n +'}).(.*)$','');
	return s.replace(re,'$1'+c+'$2');
};


function initTyniMce(ele){
	$("#" + ele).tinymce({		
		// Location of TinyMCE script
		script_url: '/javascripts/tiny_mce/tiny_mce.js',
		
		// General options
		theme: "advanced",
		plugins: "safari,advlink,inlinepopups,contextmenu,paste",
		
		// Theme options
		theme_advanced_buttons1: "bold,italic,underline|,justifyleft,justifycenter,justifyright,justifyfull,cut,copy,paste,bullist,numlist,undo,redo,link,unlink,forecolor,backcolor,code",
		theme_advanced_buttons2: "",
		theme_advanced_buttons3: "",
		theme_advanced_toolbar_location: "top",
		theme_advanced_toolbar_align: "left",
		theme_advanced_resizing: true,
		width: "500",
		height: "250",
		
		// Example content CSS (should be your site CSS)
		content_css: "/stylesheets/tinymce.css",
		
		// Drop lists for link/image/media/template dialogs
		template_external_list_url: "lists/template_list.js",
		external_link_list_url: "lists/link_list.js",
		external_image_list_url: "lists/image_list.js",
		media_external_list_url: "lists/media_list.js",
		
		// Replace values for the template plugin
		template_replace_values: {
			username: "Some User",
			staffid: "991234"
		},
		force_br_newlines:true,
		forced_root_block : '' // Needed for 3.x
	});
}


function voteCore(coreID,vote){
	if(!($("#who_voted_" + vote + " #voted_by_me").length > 0))
	{		
			$("#voted_by_me").hide(200, function(){								
				$("#vote_by_me").append("#who_voted_nothing");				
				$.getJSON("/cores/set_vote?core_id=" + coreID + "&vote=" + vote , function(data) {		
					s = data;		
				    $("#who_voted_" + vote).prepend($("#voted_by_me"));
					$("#voted_by_me").fadeIn();
					$("#core_votes_vote").text(s.vote);
					$(".core_votes_div").attr("style","background-color:" + (s.vote == "-1" ? "red;" : "green;"));
					
				});
			});			
	}
	return false;
}

function scrollWin(to){
	$('html, body').animate({
		scrollTop: ($("#" + to).offset().top - 100)
	}, 1000);
}

function changePage(ele_lnk){
	ele = $("div",ele_lnk);
	$(".page_index").attr("class","page_index");
	ele.attr("class","page_index page_index_selected");	
	$("#comments_div").slideToggle(1000,function(){		
		$(this).html("");
		//scrollWin('comments_div');
		$("#comments_div").load("/cores/get_comments",{
				page: $(ele_lnk).attr("rif"),
				core_id: $("#core_name").attr("rif")			
			},
			function(){$("#comments_div").fadeIn(1000);}
		);		
	});
	
	return false;
}


